<?php
namespace app\dao;
/**
 * @desc 采购单头表操作类
 * @author liaojianwen
 * @date 2016-12-09
 */

use yii\db\Query;
use app\dao\BaseDAO;
use yii\base\Object;
use app\enum\EnumOther;
use Yii;
use app\dao\ProcurementDetailDAO;

class ProcurementDAO extends BaseDAO
{
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2016-12-09
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'procurement';
		$this->_pKey ='procurement_id';
	}
	
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%procurement}}';
	}	
	
	/**
	 * @desc 获取采购单列表数据
	 * @author liaojianwen
	 * @date 2016-12-12
	 */
	public function getProcurements($cond, $pageInfo)
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selects = "procurement_id,procurement_no,procurement_man,vendor_id,p.warehouse_id,procurement_date,
				supplier_name,employee_name,warehouse_name,p.remark,p.finish_flag";
		
		$conditions = "p.delete_flag = :flag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
		];
		if(isset($cond['vendor']) && !empty($cond['vendor'])){
			$conditions .=" and p.vendor_id =:vid";
			$params[':vid'] =$cond['vendor'];
		}
		if(isset($cond['warehouse']) && !empty($cond['warehouse'])){
			$conditions .=" and p.warehouse_id =:wid";
			$params[':wid'] = $cond['warehouse'];
		}
		
		$userId = Yii::$app->user->id;
		$auth = Yii::$app->authManager;
		$role = $auth->getRolesByUser($userId);
		
		if (array_key_exists(EnumOther::SUP_ROLE, $role)){
			
		} else if(array_key_exists(EnumOther::BUY_ROLE, $role)){
			$conditions .=" and p.create_man =:man";
			$params[':man'] = $userId;
		} 

		$query = new Query();
		$query->select($selects)
			->from("$this->_table p")
			->leftJoin("employee e", "e.employee_id = p.procurement_man")
			->leftJoin("supplier s", "s.supplier_id = p.vendor_id")
			->leftJoin("warehouse w", "w.warehouse_id = p.warehouse_id")
			->where($conditions,$params)
			->orderBy ( ['p.finish_flag'=>SORT_ASC,'p.create_time'=>SORT_DESC]);
		
		if(isset($cond['starTime']) && !empty($cond['starTime'])){
			$query->andwhere(['between','p.procurement_date',strtotime($cond['starTime']), strtotime($cond['endTime'])]);
		}
		

		$result ['count'] = $query->count ();
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize']
		);
		return $result;
	}
	
	
	/**
	 * @desc 根据id 获取采购单单头信息
	 * @param $id //采购单id
	 * @author liaojianwen
	 * @date 2016-12-12
	 */
	public function getProcurementHead($id)
	{
		$selections = "p.procurement_id,procurement_no,procurement_date,vendor_id,p.warehouse_id,p.remark,total_amount,freight,
				vendor_id,procurement_man,p.create_man,username,procurement_amount,finish_flag,s.supplier_name vendor_name";
		$conditions = "p.procurement_id =:id";
		$params = array (
				':id' => $id,
		);
		$userId = Yii::$app->user->id;
		$auth = Yii::$app->authManager;
		$role = $auth->getRolesByUser($userId);
		
		if(array_key_exists(EnumOther::BUY_ROLE, $role)){
			$conditions .=" and p.create_man =:man";
			$params[':man'] = $userId;
		}
		$query = new Query ();
		$result = $query->select ( $selections )
		->from ("$this->_table p")
		->leftJoin("admin a","a.id= p.create_man")
		->leftJoin("supplier s","s.supplier_id = p.vendor_id")
		->where ( $conditions, $params )
		->one();
		return $result;
	}
	
	
	/**
	 * @desc 查询可导入的采购订单
	 * @author liaojianwen
	 * @date 2016-12-15
	 */
	public function selectProcurement($cond, $pageInfo)
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selects ="procurement_id,procurement_no,procurement_date,
				supplier_name,procurement_amount,p.remark";
		$conditions = "p.delete_flag = :flag and p.finish_flag = :fflag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
				':fflag'=>EnumOther::NO_FINISHED,
		];

		$query = new Query();
		$query ->select($selects)
			->from("$this->_table p")
			->leftJoin("supplier s","s.supplier_id=p.vendor_id")
			->where($conditions,$params);
		
		if(isset($cond['vendor']) && !empty($cond['vendor'])){
			$query->andwhere(['like','s.supplier_name',$cond['vendor']]);
		}
		$result ['count'] = $query->count ();
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		
		
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize']
		);
		return $result;
	}
	
	/**
	 * @desc 删除入库单更新采购单信息
	 * @author liaojianwen
	 * @date 2017-04-19
	 */
	public function updateProcurement($procurement_id, $procurement_det_id, $quantity)
	{
		$flag = $this->findByAttributes('finish_flag','procurement_id = :pid',[':pid'=>$procurement_id]);
		if($flag['finish_flag']){
			$res_hed = $this->updateByPk($procurement_id, ['finish_flag'=> 0]);
			if(!$res_hed){
				return false;
			}
		}
		
		$rest = ProcurementDetailDAO::getInstance ()->updateAllCounters ( [ 
				'received_quantity' => - $quantity,
				'minus_quantity' => $quantity 
		], 'procurement_det_id =:pid ', [ 
				':pid' => $procurement_det_id,
		] );
		if(!$rest){
			return false;
		}
			
		$det_flag = ProcurementDetailDAO::getInstance()->findByAttributes('finish_flag','procurement_det_id = :did',[':did'=>$procurement_det_id]);
		if($det_flag['finish_flag']){
			$res_det = ProcurementDetailDAO::getInstance()->updateByPk($procurement_det_id, ['finish_flag'=> 0]);
			if(!$res_det){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * @desc 采购订单明细
	 * @author liaojianwen
	 * @date 2017-09-27
	 */
	public function getExportProcurement($cond, $pageInfo, $filter)
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selects ="p.procurement_id,procurement_no,procurement_date,d.goods_id,g.product_name,u.unit_id,u.unit_name,d.base_quantity,
				s.supplier_id,supplier_name,procurement_amount,p.remark,d.price";
		$conditions = "d.delete_flag = :flag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
		];
		
		switch ($filter){
			case 0 :
				break;
			case 1:
				$conditions .=" and p.finish_flag = :cflag";
				$params[':cflag'] = EnumOther::NO_FINISHED;
				break;
			case 2:
				$conditions .=" and p.finish_flag = :cflag";
				$params[':cflag'] = EnumOther::FINISHED;
				break;
		}
		
		$query = new Query();
		$query ->select($selects)
		->from("$this->_table p")
		->leftJoin("procurement_detail d", "d.procurement_id = p.procurement_id")
		->leftJoin("product g","g.product_id = d.goods_id")
		->leftJoin("unit u", "u.unit_id = d.base_unit")
		->leftJoin("supplier s","s.supplier_id=p.vendor_id")
		->where($conditions,$params)
		->orderBy(['p.procurement_date'=>SORT_DESC,'p.procurement_id'=>SORT_DESC]);
		
		if(isset($cond['vendor']) && $cond['vendor']){
			$query->andWhere("s.supplier_id = :sid",[':sid'=>$cond['vendor']]);
		}
		
		if(isset($cond['starTime']) && !empty($cond['starTime'])){
			$query->andwhere(['between','procurement_date',strtotime($cond['starTime']), strtotime($cond['endTime'])]);
		}
		
		if(isset($cond['name']) && $cond['name']){
			$query->andwhere(['like','g.product_name',$cond['name']]);
		}
// 		dd(getSql($query));
		$result ['count'] = $query->count ();
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		
		
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize']
		);
		return $result;
	}
	
	/**
	 * @desc 导出订单明细
	 * @author liaojianwen
	 * @date 2017-09-28
	 */
	public function getExproInfo($cond)
	{
		$selects ="d.goods_id,g.product_name,u.unit_id,u.unit_name,sum(d.base_quantity) base_quantity,
				s.supplier_id,supplier_name";
		$conditions = "d.delete_flag = :flag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
		];
		
		switch ($cond['filter']){
			case 0 :
				break;
			case 1:
				$conditions .=" and p.finish_flag = :cflag";
				$params[':cflag'] = EnumOther::NO_FINISHED;
				break;
			case 2:
				$conditions .=" and p.finish_flag = :cflag";
				$params[':cflag'] = EnumOther::FINISHED;
				break;
		}
		
		$query = new Query();
		$query ->select($selects)
		->from("$this->_table p")
		->leftJoin("procurement_detail d", "d.procurement_id = p.procurement_id")
		->leftJoin("product g","g.product_id = d.goods_id")
		->leftJoin("unit u", "u.unit_id = d.base_unit")
		->leftJoin("supplier s","s.supplier_id=p.vendor_id")
		->where($conditions,$params)
		->groupBy("d.goods_id,u.unit_id,s.supplier_id");
		
		if(isset($cond['vendor']) && $cond['vendor']){
			$query->andWhere("s.supplier_id = :sid",[':sid'=>$cond['vendor']]);
		}
		
		if(isset($cond['stime']) && !empty($cond['etime'])){
			$query->andwhere(['between','procurement_date',strtotime($cond['stime']), strtotime($cond['etime'])]);
		}
		
		if(isset($cond['name']) && $cond['name']){
			$query->andwhere(['like','g.product_name',$cond['name']]);
		}
// 		dd(getSql($query));
		$result = $query->all ();
		
		return $result;
	}
}